package com.han.greedy;

import java.util.Arrays;

public class MaxHeap {

    Integer[] list = {1,2,3,4,5,11,1,7};
    int size = list.length;

    public static void main(String[] args) {
        MaxHeap maxHeap = new MaxHeap();
        maxHeap.main();

    }

    void main(){
        size = list.length;
        for (int i = size/2-1; i >= 0; i--) {
            down(i);
        }
        Arrays.stream(list).forEach(s-> System.out.print(s+" "));

    }

    public void down(int top){
        int left = top*2+1;
        int right = left+1;
        int max = top;
        if(left<size && list[max]<list[left]){
            //做交换
            max = left;
        }

        if(right<size && list[max]<list[right]){
            //做交换
            max = right;
        }

        if(max != top){
            swap(top, max);
            down(max);
            System.out.println("into down");
        }

    }

    private void swap(int top, int replaceNum) {
        int temp = list[top];
        list[top] = list[replaceNum];
        list[replaceNum] = temp;
    }
}
